<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传试卷扫描件"
    width="50%"
    :before-close="handleClose"
    class="upload-scan-dialog"
  >
    <div class="upload-scan-content">
      <div class="student-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">
            {{ submission ? submission.student_id : '' }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ submission ? submission.student_name : '' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-form :model="form" ref="formRef" label-width="120px">
        <el-form-item label="选择文件" prop="file" :rules="fileRules">
          <el-upload
            class="upload-demo"
            drag
            multiple
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip">支持上传扫描件文件（PDF, JPG, PNG），不超过50MB</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div v-if="fileList.length" class="uploaded-files">
        <h4>已选择文件：</h4>
        <el-card shadow="never" class="attachment-list">
          <div v-for="file in fileList" :key="file.uid" class="attachment-item">
            <i class="el-icon-document"></i>
            {{ file.name }}
            <span class="file-size">{{ formatFileSize(file.size) }}</span>
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          :loading="uploading"
          :disabled="fileList.length === 0"
        >
          {{ uploading ? '上传中...' : '确认上传' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  examId: {
    type: [String, Number],
    required: true
  },
  submission: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['update:visible', 'uploaded'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const form = ref({})
const fileList = ref([])
const uploading = ref(false)
const formRef = ref(null)

const submissionId = computed(() => {
  return props.submission ? props.submission.submission_id : null
})

const fileRules = [
  { required: true, message: '请上传试卷扫描件', trigger: 'change' }
]

const formatFileSize = (size) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

const beforeUpload = (file) => {
  const isValidType = ['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValidType) {
    ElMessage.error('只能上传 PDF/JPG/PNG 格式的文件！')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB！')
    return false
  }
  return true
}

// 修复文件改变处理函数
const handleFileChange = (file, uploadFileList) => {
  fileList.value = uploadFileList
}

// 添加文件移除处理函数
const handleFileRemove = (file, uploadFileList) => {
  fileList.value = uploadFileList
}

const submitForm = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  if (!submissionId.value) {
    ElMessage.error('无效的提交记录')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    fileList.value.forEach(file => {
      formData.append('files', file.raw || file)
    })

    await axios.post(
        `/backend/api/exam/submission/${submissionId.value}/upload_attachments/`,
        formData,
        {
          headers: {'Content-Type': 'multipart/form-data'},
          withCredentials: true
        }
    )

    ElMessage.success('扫描件上传成功')
    emit('uploaded')
    handleClose()
  } catch (error) {
    console.error('上传扫描件失败:', error)
    ElMessage.error('上传扫描件失败，请重试')
  } finally {
    uploading.value = false
  }
}

const handleClose = () => {
  fileList.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('update:visible', false)
}
</script>

<style scoped>
.upload-scan-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.upload-scan-content {
  padding: 20px;
}

.student-info {
  margin-bottom: 20px;
}

.uploaded-files {
  margin-top: 20px;
}

.attachment-list {
  background-color: #f8f9fa;
}

.attachment-item {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.attachment-item:last-child {
  border-bottom: none;
}

.file-size {
  color: #909399;
  font-size: 12px;
  margin-left: auto;
}
</style>